package com.feiyisys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feiyisys.common.PageResult;
import com.feiyisys.common.Result;
import com.feiyisys.entity.Category;
import com.feiyisys.entity.Comment;
import com.feiyisys.entity.CulturalHeritage;
import com.feiyisys.service.CommentService;
import com.feiyisys.service.CulturalHeritageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private CulturalHeritageService culturalHeritageService;

    @GetMapping
    public Result<IPage<Comment>> getPage(@RequestParam(defaultValue = "1") Long current,
                                          @RequestParam(defaultValue = "10") Long size) {
        Page<Comment> page = new Page<>(current, size);
        IPage<Comment> result = commentService.page(page);

        // 填充非遗名称信息
        fillHeritageNames(result.getRecords());

        return Result.success(result);
    }
    /**
     * 根据名字模糊查询分类
     */

    @GetMapping("/searchbycontent")
    public Result<IPage<Comment>> searchByContent(@RequestParam String content,
                                                  @RequestParam(defaultValue = "1") Long current,
                                                  @RequestParam(defaultValue = "10") Long size) {
        Page<Comment> page = new Page<>(current, size);
        IPage<Comment> result = commentService.page(page,
                new QueryWrapper<Comment>().like("content", content));

        // 填充非遗名称信息
        fillHeritageNames(result.getRecords());

        return Result.success(result);
    }

    /**
     * 填充评论记录中的非遗名称
     */
    private void fillHeritageNames(List<Comment> comments) {
        if (comments == null || comments.isEmpty()) {
            return;
        }

        // 收集所有不同的非遗ID
        Set<Long> heritageIds = comments.stream()
                .map(Comment::getCulturalHeritageId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        if (heritageIds.isEmpty()) {
            return;
        }

        // 批量查询非遗信息
        List<CulturalHeritage> heritages = culturalHeritageService.listByIds(heritageIds);
        Map<Long, String> heritageNameMap = heritages.stream()
                .collect(Collectors.toMap(CulturalHeritage::getId, CulturalHeritage::getName));

        // 为每个评论设置非遗名称（通过扩展字段）
        for (Comment comment : comments) {
            if (comment.getCulturalHeritageId() != null) {
                // 使用反射或添加临时字段方式设置名称
                comment.setHeritageName(heritageNameMap.getOrDefault(comment.getCulturalHeritageId(), "未知非遗"));
            }
        }
    }
    /**
     * 根据ID获取评论
     */
    @GetMapping("/{id}")
    public Result<Comment> getCommentById(@PathVariable Long id) {
        Comment comment = commentService.getById(id);
        return Result.success(comment);
    }

    /**
     * 创建顶级评论（parentId默认为0）
     */
    @PostMapping("/top")
    public Result<Boolean> createTopComment(@RequestBody Comment comment) {
        comment.setParentId(0L); // 设置为顶级评论
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());
        comment.setStatus((byte) 1); // 默认正常显示
        boolean saved = commentService.save(comment);
        if (saved) {
            return Result.success(saved);
        } else {
            return Result.fail("评论发布失败");
        }
    }

    /**
     * 创建回复评论（需传入parentId）
     */
    @PostMapping("/reply")
    public Result<Boolean> createReplyComment(@RequestBody Comment comment) {
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());
        comment.setStatus((byte) 1); // 默认正常显示
        // 验证父评论是否存在
        if (comment.getParentId() == null || comment.getParentId() <= 0) {
            return Result.fail("回复评论必须提供有效的父评论ID");
        }

        boolean saved = commentService.save(comment);
        if (saved) {
            return Result.success(saved);
        } else {
            return Result.fail("回复发布失败");
        }
    }

    /**
     * 更新评论
     */
    @PutMapping
    public Result<Boolean> updateComment(@RequestBody Comment comment) {
        comment.setUpdateTime(new Date());
        boolean updated = commentService.updateById(comment);
        if (updated) {
            return Result.success(updated);
        } else {
            return Result.fail("评论更新失败");
        }
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteComment(@PathVariable Long id) {
        boolean removed = commentService.removeById(id);
        if (removed) {
            return Result.success(removed);
        } else {
            return Result.fail("评论删除失败");
        }
    }
    /**
     * 根据文化遗产ID获取评论列表
     */
    @GetMapping("/heritage/{culturalHeritageId}")
    public Result<IPage<Comment>> getCommentsByHeritageId(
            @PathVariable Long culturalHeritageId,
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size) {
        Page<Comment> page = new Page<>(current, size);
        IPage<Comment> result = commentService.page(page,
                new QueryWrapper<Comment>()
                        .eq("cultural_heritage_id", culturalHeritageId)
                        .eq("status", 1)  // 只获取状态为1(正常显示)的评论
                        .orderByDesc("create_time"));
        return Result.success(result);
    }
}
